/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Common;

import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author harish
 */
public class XMLParser
{
     
     public static String Parse(String element,String attribute,Document doc)
     {
        try
        {            
            return doc.getElementsByTagName(attribute).item(0).getChildNodes().item(0).getNodeValue();
        }
        catch(Exception e)
        {
            try
            {
            Log.GetInstance().Write("Error in parsing XML for configuration:" + e.getMessage());
            }
            catch(IOException i)
            {

            }        
            return "";
        }
     }
     
     private static String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}


	/**
	 * Calls getTextValue and returns a int value
	 */
	private static int getIntValue(Element ele, String tagName) 
        {
		//in production application you would catch the exception
		return Integer.parseInt(getTextValue(ele,tagName));
	}

     public static Document PrepareDoc(String s)
     {
         try
         {
            File file=new File(s);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            return doc;
         }
         catch(org.xml.sax.SAXException spe)
         {
            try
            {
            Log.GetInstance().Write("Error in parsing XML for configuration" + spe.getMessage());
            }
            catch(IOException i)
            {

            }        
            return null;
         }
         catch(javax.xml.parsers.ParserConfigurationException pce)
         {
            try
            {
            Log.GetInstance().Write("Error in parsing XML for configuration" + pce.getMessage());
            }
            catch(IOException i)
            {

            }        
            return null;
         }
         catch(IOException e)
         {
            try
            {
            Log.GetInstance().Write("Error in parsing XML for configuration" + e.getMessage());
            }
            catch(IOException i)
            {

            }        
            return null;
         }
     }
}
